package com.lakers.notice.springboot.netty;

import cn.hutool.core.map.MapUtil;
import com.lakers.notice.springboot.model.NoticeUserInfo;
import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 功能描述: UserChannelCtxMap
 *
 * @author liqin(zxl)
 * @date 2024/5/3
 */
public class UserChannelCtxMap {

    private static final Map<String, Map<Integer, ChannelHandlerContext>> CHANNEL_MAP = new ConcurrentHashMap<>(32);


    public static void addChannelCtx(String userId, Integer channel, ChannelHandlerContext ctx) {
        CHANNEL_MAP.computeIfAbsent(userId, key -> new ConcurrentHashMap<>(4)).put(channel, ctx);
    }



    public static void removeChannelCtx(String userId, Integer terminal) {
        if (userId != null && terminal != null && CHANNEL_MAP.containsKey(userId)) {
            Map<Integer, ChannelHandlerContext> userChannelMap = CHANNEL_MAP.get(userId);
            userChannelMap.remove(terminal);
            if (MapUtil.isEmpty(userChannelMap)){
                CHANNEL_MAP.remove(userId);
            }
        }
    }

    public static ChannelHandlerContext getChannelCtx(String userId, Integer terminal) {
        if (userId != null && terminal != null && CHANNEL_MAP.containsKey(userId)) {
            Map<Integer, ChannelHandlerContext> userChannelMap = CHANNEL_MAP.get(userId);
            if (userChannelMap.containsKey(terminal)) {
                return userChannelMap.get(terminal);
            }
        }
        return null;
    }


    public static List<ChannelHandlerContext> getAll(NoticeUserInfo sender){
        List<ChannelHandlerContext> result = new ArrayList<>();
        for (Map.Entry<String, Map<Integer, ChannelHandlerContext>> entry : CHANNEL_MAP.entrySet()) {
            if (sender.getUserId().equals(entry.getKey())){
                continue;
            }
            result.addAll(entry.getValue().values());
        }
        return result;
    }


    public static Map<String, Map<Integer, ChannelHandlerContext>> getAll(){
        return CHANNEL_MAP;
    }





}
